<template>
  <uni-list-chat
    v-for="course in courseList"
    :key="course.id"
    :title="course.title"
    :avatar="course.cover"
    :note="`${course.buyCount}人购买`"
    :to="`/pages/course/detail/index?id=${course.id}`"
  >
    <view class="chat-custom-right"> ￥ {{ course.price }} </view>
  </uni-list-chat>
  <uni-load-more :status="status" />
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { getCourseListApi } from "@/api/course";
import type { CourseList } from "@/api/types";
import { onReachBottom, onShow } from "@dcloudio/uni-app";

// more: 加载前 loading: 加载中 no-more: 没有数据
const status = ref("more");

onReachBottom(async () => {
  if (page.value >= totalPages.value) return;
  page.value++;
  status.value = "loading";
  await getCourseList();
  if (page.value >= totalPages.value) {
    status.value = "no-more";
  } else {
    status.value = "more";
  }
});

// 分页
const page = ref(1);
const limit = ref(10);
const totalPages = ref(0);
const courseList = ref<CourseList>([]);

const getCourseList = async () => {
  const res = await getCourseListApi(page.value, limit.value);
  totalPages.value = res.pages;
  if (page.value === 1) {
    courseList.value = res.items;
  } else {
    courseList.value = [...courseList.value, ...res.items];
  }
};

onShow(() => {
  page.value = 1;
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0,
  });
  getCourseList();
});
</script>

<style lang="scss">
.uni-list-chat__content-extra {
  justify-content: center !important;
  color: red;
}
</style>
